/**
 * 
 */

package lohmar.ashar.android.batterySaver.helper;

import android.content.ContentResolver;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.view.Window;
import android.view.WindowManager;

/**
 * @author Mihai HARAS (Lohmar ASHAR) 2011
 */
public class LightHelper {
    private static final String PROP_MODE       = Settings.System.SCREEN_BRIGHTNESS_MODE;
    private static final String PROP_BRIGHTNESS = Settings.System.SCREEN_BRIGHTNESS;
    private static final int    MODE_AUTOMATIC  = Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;
    private static final int    MODE_MANUAL     = Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL;
    private ContentResolver     contentResolver;
    private Window              window;

    public LightHelper(ContentResolver contentResolver, Window window) {
        this.contentResolver = contentResolver;
        this.window = window;
    }

    public boolean isBrightnessAutomatic() {
        return Settings.System.getInt(contentResolver, PROP_MODE, -1) == MODE_AUTOMATIC;
    }

    public void setBrightnessAutomatic(boolean brightnessAutomatic) {
        int iBrightnessAutomatic = brightnessAutomatic ? MODE_AUTOMATIC : MODE_MANUAL;
        Settings.System.putInt(contentResolver, PROP_MODE, iBrightnessAutomatic);
    }

    public void setScreenBrighteness(int brightness) {
        WindowManager.LayoutParams lp = window.getAttributes();
        brightness = Math.max(brightness, 10);
        Settings.System.putInt(contentResolver, PROP_BRIGHTNESS, brightness);
        lp.screenBrightness = brightness / 255.0f;
        window.setAttributes(lp);
    }

    public int getScreenBrighteness() {
        int curBrightnessValue = -1;
        try {
            curBrightnessValue = Settings.System.getInt(contentResolver, PROP_BRIGHTNESS);
        } catch (SettingNotFoundException e) {
            e.printStackTrace();
        }
        return curBrightnessValue;
    }

}
